//
//  LocalBooksViewController.swift
//  Reader
//
//  Created by home on 2019/10/10.
//  Copyright © 2019 codeguesser. All rights reserved.
//

import UIKit
import SwiftyJSON
import Alamofire
import WebKit
class LocalBooksViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    @IBOutlet weak var tableView:UITableView!
    var dataList:[JSON] = []{
        didSet{
            self.tableView.reloadData()
        }
    }
    //MARK: - system methods
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.title = "本地书店"
        self.dataList.append(contentsOf: (BookModel.findAll()?.toJSON() ?? []))
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(cleanData))
    }
    //MARK: - tableview methods
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .value1, reuseIdentifier: UITableViewCell.identifier)
        cell.textLabel?.text = dataList[indexPath.row]["name"].stringValue
        cell.detailTextLabel?.text = dataList[indexPath.row]["id"].stringValue
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        let vc = ChapterViewController(nibName: ChapterViewController.identifier)
        vc.addOrRemoveAction = {[weak self] in
            if let SSelf = self{
                SSelf.dataList = (BookModel.findAll()?.toJSON() ?? [])
            }
        }
        vc.data = dataList[indexPath.row]
        self.navigationController?.pushViewController(vc, animated: true)
    }
    //MARK: - custom methods
    @objc func cleanData(){
        URLCache.shared.removeAllCachedResponses()
        WKWebsiteDataStore.default()
        UIAlertController.alertMessage("清理完毕")
    }
}
